import {ExclamationCircleOutlined, PlusOutlined} from '@ant-design/icons';
import {Button, Divider, Drawer, Form, Input, message, Modal, Select, Tag, InputNumber} from 'antd';
import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import ProDescriptions from '@ant-design/pro-descriptions';
import MaterialForm from './components/MaterialForm';
import {addRule, offSale, onSale, queryRule, removeRule, updateRule} from './service';


const initRecord = {
  materialCode: '',
  materialName: '',
  materialUnit: '',
  materialPrice: '',
  materialSupplier: '',
  remark: ''
}


const TableList = () => {
  const [createModalVisible, handleModalVisible] = useState(false);
  const [selectedRow, setSelectedRow] = useState({});
  const [formTitle, setFormTitle] = useState('新增物料');
  const actionRef = useRef();
  const [formRef] = Form.useForm();
  const [row, setRow] = useState();
  const [selectedRowsState, setSelectedRows] = useState([]);
  const {Option} = Select;
  const handleUpdateModalVisible = (record) => {
    formRef.setFieldsValue({
      ...record,
      materialId: record.materialId
    })
    setFormTitle('更新物料')
    setSelectedRow(record)
    handleModalVisible(true)
  }
  const handleCreateModalVisible = () => {
    formRef.setFieldsValue({
      ...initRecord
    })
    setFormTitle('新增物料')
    handleModalVisible(true)
  }
  /**
   * 添加节点
   *
   * @param fields
   */

  const handleAdd = async (fields) => {
    const hide = message.loading('正在添加');

    try {
      hide();
      await addRule({...fields}).then((res) => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success(res.message);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
          return false;
        }
      });
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
    return true;
  };
  /**
   * 更新节点
   *
   * @param fields
   */

  const handleUpdate = async (fields) => {
    const hide = message.loading('正在更新');

    try {
      hide();
      await updateRule({...fields}).then((res) => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success(res.message);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
          return false;
        }
        return true;
      });
    } catch (error) {
      hide();
      message.error('更新失败请重试！');
      return false;
    }
    return true;
  };
  /**
   * 删除节点
   *
   * @param selectedRows
   */

  const handleRemove = async (selectedRows) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      hide();
      await removeRule({...selectedRows}).then((res) => {
        if (res && res.status === '0') {
          handleModalVisible(false)
          message.success(res.message);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } else {
          message.error(res.message);
          return false;
        }
        return true;
      });
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  const handleOnOffSale = async (fields) => {
    try {
      if (fields.materialStatus === 1) {
        await offSale({...fields}).then((res) => {
          if (res && res.status === '0') {
            message.success(res.message);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          } else {
            message.error(res.message);
            return false;
          }
          return true;
        });
      }else {
        await onSale({...fields}).then((res) => {
          if (res && res.status === '0') {
            message.success(res.message);
          } else {
            message.error(res.message);
            return false;
          }
          return true;
        });
      }
      if (actionRef.current) {
        actionRef.current.reload();
      }

    } catch (error) {
      message.error('请联系管理员');
      return false;
    }
  }

  const deleteConfig = (record) => {
    Modal.confirm({
      title: '注意',
      icon: <ExclamationCircleOutlined/>,
      content: `是否要删除物料编码为 【${record.materialCode} 】的物料？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async ()=>{
        const success = await handleRemove(record)
      }
    });
  };

  const onSubmit = async (materialStatus) => {
    formRef.validateFields().then(value => {
      const param = value;
      let success;
      if (formTitle === '更新物料') {
        param.materialId = selectedRow.materialId
        param.materialStatus = 1;
        success = handleUpdate(param)
      }else {
        param.materialStatus = materialStatus;
        success = handleAdd(param)
      }

      if (success) {
        handleModalVisible(false);
      }
    })

  }

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '物料编码',
      dataIndex: 'materialCode',
      tip: '物料编码是唯一的',
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '物料编码最大长度为32'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '物料编码是必填项'
          }
        ],
      },
      valueType: 'input',
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={formTitle === '更新物料'&& type === 'form'} maxLength={33} {...fieldProps} placeholder={'请输入物料编码 格式为A0'}/>;
      }
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '物料名称最大长度为32'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '物料名称是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={33} placeholder={'请输入物料名称'}/>;
      }
    },
    {
      title: '计量单位',
      dataIndex: 'materialUnit',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '计量单位是必选项'
          },
          {
            max: 32,
            message: '计量单位最大长度为32'
          },
        ],
      },
      // renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
      //   return <Select>
      //     <Option value="个">个</Option>
      //     <Option value="台">台</Option>
      //     <Option value="块">块</Option>
      //   </Select>;
      // }
    },
    {
      title: '单价（元）',
      dataIndex: 'materialPrice',
      sorter: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '单价是必填项'
          },
          {
            pattern: /^\d+(\.\d{0,2})?$/,
            message: '只能输入两位小数'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <InputNumber
          style={{width: '100%'}}
          placeholder={'请输入单价'}
          min={0.01}
          max={99999999.99}
          step={0.01}
          stringMode
        />;
      }
    },
    {
      title: '供应商',
      dataIndex: 'materialSupplier',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '供应商最大长度为32'
          },
        ],
      },
      // renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
      //   return <Select defaultValue="A材料有限公司">
      //     <Option value="A材料有限公司">A材料有限公司</Option>
      //     <Option value="B打印机公司">B打印机公司</Option>
      //     <Option value="C供应商">C供应商</Option>
      //   </Select>;
      // }
    },
    {
      title: '状态',
      dataIndex: 'materialStatus',
      sorter: true,
      hideInForm: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select defaultValue={-1}>
          <Option value={-1}>全部</Option>
          <Option value={0}>草稿</Option>
          <Option value={1}>已上架</Option>
          <Option value={2}>已下架</Option>
        </Select>;
      },
      render: (text, record, index) => {
        return (
          <Tag color={text === 0 ? 'magenta' :
            text === 1 ? 'green' : 'red'
          }>{text === 0 ? '草稿' :
            text === 1 ? '已上架' : '已下架'}</Tag>
        )
      }
    },
    // {
    //   title: '创建人',
    //   dataIndex: 'createBy',
    //   hideInSearch: true,
    //   hideInForm: true
    // },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a onClick={() => setRow(record)}>
          详情
        </a>,
        <Divider type="vertical" style={{display: record.materialStatus === 0 ? 'block' : 'none'}}/>,
        <a style={{display: record.materialStatus === 0 ? 'block' : 'none'}}
           onClick={() => handleUpdateModalVisible(record)}>修改</a>,
        <Divider type="vertical"/>,
        <a onClick={()=>handleOnOffSale(record)}>{record.materialStatus === 1 ? '下架' : '上架'}</a>,
        <Divider style={{display: record.materialStatus === 0 ? 'block' : 'none'}} type="vertical"/>,
        <a style={{display: record.materialStatus === 0 ? 'block' : 'none'}}
           onClick={() => deleteConfig(record)}>删除</a>,
      ],
    },
  ];
  const detailColumns = [
    {
      title: '序号',
      dataIndex: 'key',
      hideInForm: true,
      hideInSearch: true,
      render: (text, record, index, action) => {
        return `${index + 1}`
      }
    },
    {
      title: '物料编码',
      dataIndex: 'materialCode',
      tip: '物料编码是唯一的',
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '物料编码最大长度为32'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '物料编码是必填项'
          }
        ],
      },
      valueType: 'input',
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input disabled={formTitle === '更新物料'&& type === 'form'} maxLength={33} {...fieldProps} placeholder={'请输入物料编码 格式为A0'}/>;
      }
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '物料名称最大长度为32'
          },
          {
            whitespace: true,
            message: '请不要输入空格'
          },
          {
            required: true,
            message: '物料名称是必填项'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Input maxLength={33} placeholder={'请输入物料名称'}/>;
      }
    },
    {
      title: '计量单位',
      dataIndex: 'materialUnit',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '计量单位是必选项'
          },
          {
            max: 32,
            message: '计量单位最大长度为32'
          },
        ],
      },
      // renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
      //   return <Select>
      //     <Option value="个">个</Option>
      //     <Option value="台">台</Option>
      //     <Option value="块">块</Option>
      //   </Select>;
      // }
    },
    {
      title: '单价',
      dataIndex: 'materialPrice',
      sorter: true,
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '单价是必填项'
          },
          {
            pattern: /^\d+(\.\d{0,2})?$/,
            message: '只能输入两位小数'
          }
        ],
      },
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <InputNumber
          style={{width: '100%'}}
          placeholder={'请输入单价'}
          formatter={value => `${value}元`}
          parser={value => value.replace('元', '')}
          min={0.01}
          max={99999999.99}
          step={0.01}
          stringMode
        />;
      }
    },
    {
      title: '供应商',
      dataIndex: 'materialSupplier',
      hideInSearch: true,
      formItemProps: {
        rules: [
          {
            max: 32,
            message: '供应商最大长度为32'
          },
        ],
      },
      // renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
      //   return <Select defaultValue="A材料有限公司">
      //     <Option value="A材料有限公司">A材料有限公司</Option>
      //     <Option value="B打印机公司">B打印机公司</Option>
      //     <Option value="C供应商">C供应商</Option>
      //   </Select>;
      // }
    },
    {
      title: '状态',
      dataIndex: 'materialStatus',
      sorter: true,
      hideInForm: true,
      renderFormItem: (_, {type, defaultRender, formItemProps, fieldProps, ...rest}, form) => {
        return <Select defaultValue={-1}>
          <Option value={-1}>全部</Option>
          <Option value={0}>草稿</Option>
          <Option value={1}>已上架</Option>
          <Option value={2}>已下架</Option>
        </Select>;
      },
      render: (text, record, index) => {
        return (
          <Tag color={text === 0 ? 'magenta' :
            text === 1 ? 'green' : 'red'
          }>{text === 0 ? '草稿' :
            text === 1 ? '已上架' : '已下架'}</Tag>
        )
      }
    },
    // {
    //   title: '创建人',
    //   dataIndex: 'createBy',
    //   hideInSearch: true,
    //   hideInForm: true
    // },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true
    },
    {
      title: '备注',
      dataIndex: 'remark',
      valueType: 'textarea',
      hideInSearch: true,
      hideInTable: true
    },
  ];
  return (
    <PageContainer>
      <ProTable
        actionRef={actionRef}
        rowKey="materialCode"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button type="primary" onClick={() => handleCreateModalVisible()}>
            <PlusOutlined/> 新建
          </Button>,
        ]}
        request={async (params, sorter, filter) => {
          const param = {...params, pageNum: params.current};
          if (param.materialStatus === -1) {
            param.materialStatus = null;
          }
          const res = await queryRule(param)
          return {
            data: res.result.records,
            success: true,
            total: res.result.total
          }
        }}
        columns={columns}
      />
      <MaterialForm title={formTitle} onCancel={() => handleModalVisible(false)} modalVisible={createModalVisible}
                    onSubmit={(materialStatus) => onSubmit(materialStatus)}>
        <ProTable
          onSubmit={async (value) => {
            const success = await handleAdd(value);

            if (success) {
              handleModalVisible(false);

              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          form={{
            form: formRef,
            layout: 'horizontal',
            labelAlign: 'left'
          }}
          rowKey="key"
          type="form"
          columns={columns}
        />
      </MaterialForm>

      <Drawer
        width={600}
        visible={!!row}
        onClose={() => {
          setRow(undefined);
        }}
        closable={false}
      >
        {row?.materialCode && (
          <ProDescriptions
            column={2}
            title={row?.materialCode}
            request={async () => ({
              data: row || {},
            })}
            params={{
              id: row?.materialCode,
            }}
            columns={detailColumns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
